<template>
  <Dialog v-model="dialogVisible" title="公海导入" width="400">
    <el-form ref="formRef" :rules="rules" label-position="left" :model="form">
      <el-form-item prop="customerType" label="客户类型">
        <el-select v-model="form.customerType">
          <el-option
            v-for="item in CustomerTypeOptions"
            :key="item.label"
            :value="item.value"
            :label="item.label"
          /> </el-select
      ></el-form-item>
    </el-form>
    <el-upload
      ref="uploadRef"
      v-model:file-list="fileList"
      :action="importUrl"
      :auto-upload="false"
      :disabled="formLoading"
      :headers="uploadHeaders"
      :limit="1"
      :on-error="submitFormError"
      :on-exceed="handleExceed"
      :on-success="submitFormSuccess"
      accept=".xlsx, .xls"
      :data="uploadData"
      drag
    >
      <Icon icon="ep:upload" />
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <template #tip>
        <div class="el-upload__tip text-center">
          <span>仅允许导入 xls、xlsx 格式文件。</span>
          <el-link
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            type="primary"
            @click="importTemplate"
          >
            下载模板
          </el-link>
        </div>
      </template>
    </el-upload>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="close">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import { getImportTemplateCustomer } from '@/api/customer'
import { getAccessToken, getTenantId } from '@/utils/auth'
import download from '@/utils/download'
import { CustomerTypeOptions } from '@/mock'
import { ElForm } from 'element-plus'

defineOptions({ name: 'SystemUserImportForm' })

const message = useMessage() // 消息弹窗
// ----------------------------- 表单 -----------------------------
const formRef = ref<InstanceType<typeof ElForm> | null>(null)
const rules = reactive({
  customerType: [{ required: true, message: '请选择客户类型', trigger: 'change' }]
})
const form = ref({
  customerType: ''
})
const close = () => {
  form.value.customerType = ''
  dialogVisible.value = false
  fileList.value = []
}
// ----------------------------- 弹窗状态 -----------------------------
const dialogVisible = ref(false) // 弹窗的是否展示
/** 打开弹窗 */
const open = () => {
  dialogVisible.value = true
  fileList.value = []
  form.value.customerType = ''
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗
const formLoading = ref(false)
// ----------------------------- 上传 -----------------------------
const uploadRef = ref()
const importUrl =
  import.meta.env.VITE_BASE_URL + import.meta.env.VITE_API_URL + '/crm/customer/import'
const uploadHeaders = ref() // 上传 Header 头
const fileList = ref([]) // 文件列表
const uploadData = computed(() => {
  return { level: form.value.customerType }
})
/** 提交表单 */
const submitForm = async () => {
  if (fileList.value.length == 0) {
    message.error('请上传文件')
    return
  }
  console.log('123')
  try {
    await formRef?.value?.validate()
    console.log('456')
    formLoading.value = true
    // 提交请求
    uploadHeaders.value = {
      Authorization: 'Bearer ' + getAccessToken(),
      'tenant-id': getTenantId()
    }
    await uploadRef.value!.submit()
    console.log('789')
    formLoading.value = false
  } catch (e) {
    console.error(e)
    formLoading.value = false
  }
}
/** 文件上传成功 */
const emits = defineEmits(['success'])
const submitFormSuccess = (response: any) => {
  if (response.code !== 0) {
    message.error('请上传符合标准的文件')
    uploadRef.value?.clearFiles()
    return
  }
  if (response.code === 0) {
    message.success('导入成功')
    uploadRef.value?.clearFiles()
    close()
    emits('success')
  }
}
/** 上传错误提示 */
const submitFormError = (): void => {
  message.error('上传失败，请您重新上传！')
  formLoading.value = false
}
/** 文件数超出提示 */
const handleExceed = (): void => {
  message.error('最多只能上传一个文件！')
}
/** 下载模板操作 */
const importTemplate = async () => {
  const res = await getImportTemplateCustomer()
  download.excel(res, '公海导入模版.xls')
}
</script>
